package com.tanhua.server.service;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.server.pojo.RecommendUser;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.RecommendUserQueryParam;
import com.tanhua.server.vo.TodayBest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * @author feihao
 * @version 1.0
 * @date 2021/6/29 20:19
 */

@Service
public class TodayBestService {

    @Autowired
    private RecommendUserService recommendUserService;


    @Autowired
    private UserInfoService userInfoService;

    @Value("${tanhua.sso.default.user}")   // 2号
    private Long defaultUserId;

    public TodayBest findTodayBest() {

        //校验token:
        User user = UserThreadLocal.get();

        //token 查到user:调用查询今日佳人的service:
        TodayBest todayBest = recommendUserService.queryTodayBest(user.getId());

        if (todayBest == null) {
            todayBest = new TodayBest();
            //如果没有推荐的人，给他默认一个：
            todayBest.setId(defaultUserId);
            todayBest.setFateValue(78L);   //设置，默认固定的缘分值78
        }

        //补全个人信息：
        UserInfo userInfo = userInfoService.queryTodayBestInfo(todayBest.getId());
        todayBest.setAvatar(userInfo.getLogo());
        todayBest.setNickname(userInfo.getNickName());
        todayBest.setTags(userInfo.getTags().split(","));
        todayBest.setGender(userInfo.getSex().getValue() == 1 ? "man" : "woman");
        todayBest.setAge(userInfo.getAge());

        return todayBest;
    }

    public PageResult findRecommendation( RecommendUserQueryParam param) {
        //校验token:
        User user = UserThreadLocal.get();
        //token没问题：封装pageResult对象：
        PageResult pageResult = new PageResult();
        pageResult.setPage(param.getPage());
        pageResult.setPagesize(param.getPagesize());

        //查询推荐列表：
        PageInfo<RecommendUser> pageInfo = recommendUserService.findRecommendationUserList(user.getId(), param.getPage(), param.getPagesize());
        List<RecommendUser> records = pageInfo.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            //如果查询的列表为空.给他返回空
            return pageResult;
        }

        //不为空：进行个人信息封装：
        //获取被推荐人的id:
        Map<Long, Long> map = new HashMap<>();
        for (RecommendUser record : records) {
            Long userId = record.getUserId();
            Double score = record.getScore();
            map.put(userId, score.longValue());
        }

        //拿出UseID,进行去mysql查询相应的userInfo:
        Set<Long> userIdSet = map.keySet();

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIdSet);
        if (StringUtils.isNotEmpty(param.getGender())) {
            //需要性别参数查询
//            queryWrapper.eq("sex", StringUtils.equals(param.getGender(), "man") ? 1 : 2);
        }

        if (StringUtils.isNotEmpty(param.getCity())) {
            //需要城市参数查询
//            queryWrapper.like("city", param.getCity());
        }

        if (param.getAge() != null) {
            //设置年龄参数，条件：小于等于
//            queryWrapper.le("age", param.getAge());
        }

        List<UserInfo> userInfos = userInfoService.queryRecommendationUserInfo(queryWrapper);

        if (userInfos.size() == 0) {
            //没有推荐人信息：
            return pageResult;
        }

        //不为空。则进行userInfo信息封装：
        //创建集合存储推荐人：
        List<TodayBest> todayBests = new ArrayList<>();
        TodayBest todayBest = null;
        for (UserInfo userInfo : userInfos) {
            todayBest = new TodayBest();
            todayBest.setId(userInfo.getUserId());
            todayBest.setAvatar(userInfo.getLogo());
            todayBest.setNickname(userInfo.getNickName());
            todayBest.setTags(StringUtils.split(userInfo.getTags(), ','));
            todayBest.setGender(userInfo.getSex().getValue() == 1 ? "man" : "woman");
            todayBest.setAge(userInfo.getAge());
            todayBest.setFateValue(map.get(userInfo.getId()));
            todayBests.add(todayBest);
        }

        //将集合按照缘分值降序排序：
        Collections.sort(todayBests, new Comparator<TodayBest>() {
            @Override
            public int compare(TodayBest o1, TodayBest o2) {
                return (int) (o2.getFateValue() - o1.getFateValue());
            }
        });

        //写入pageResult:

        System.out.println(todayBests);
        pageResult.setItems(todayBests);

        return pageResult;
    }
}
